package com.jwsoft.manager.core.dao.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.module.base.common.util.CommonSecureUtil;
import com.bifang.module.base.common.vo.common.CommonVO;
import com.bifang.module.base.core.integration.CommonIntegration;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.constant.EduCache;
import com.jwsoft.manager.common.vo.eduStudentHouse.EduStudentHouseByRealpVO;
import com.jwsoft.manager.common.vo.eduStudentHouse.EduStudentHouseQueryByRealpVO;
import com.jwsoft.manager.common.vo.eduStudentHouse.EduStudentHouseVO;
import com.jwsoft.manager.core.dao.model.*;
import com.jwsoft.manager.core.dao.mapper.EduStudentHouseMapper;
import com.jwsoft.manager.core.dao.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 录取学生房产信息表服务实现类
 *
 * @author wangtao
 * @since 2022-12-01
 */
@Service
public class EduStudentHouseServiceImpl extends ServiceImpl<EduStudentHouseMapper, EduStudentHouse> implements EduStudentHouseService {
    @Autowired
    EduHouseDetailService eduHouseDetailService;
    @Autowired
    EduHouseService eduHouseService;
    @Autowired
    CommonIntegration commonIntegration;
    @Autowired
    EduhHouseDetailService eduhHouseDetailService;
    @Autowired
    EduhHouseService eduhHouseService;
    @Override
    public PageInfo<EduStudentEnroll> queryInit(Integer year) {
        PageHelper.startPage(1,1000);
        List<EduStudentEnroll> list = this.baseMapper.queryInit(year);
        PageInfo<EduStudentEnroll> pageInfo=new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    @Cached(name = EduCache.REAL_PROPERTY_USER_KEY, key = "#vo.realProperty", cacheType = CacheType.BOTH, expire = 86400, localExpire = 20)
    public List<EduStudentHouseVO> getListByRealp(EduStudentHouseQueryByRealpVO vo) {
        //加密查询条件
        String encrypt = CommonSecureUtil.sm4Encrypt(vo.getRealProperty());

        QueryWrapper<EduHouseDetail> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().select(EduHouseDetail::getHouseId).eq(EduHouseDetail::getRealProperty,vo.getRealProperty());

        List<String> houseIdList=new ArrayList<>();
        boolean flag=true;

        //查询原始表，如果没有数据就去历史表查询
        List<EduHouseDetail> details=eduHouseDetailService.list(queryWrapper);
        if(CollectionUtils.isEmpty(details)){
            QueryWrapper<EduhHouseDetail> queryWrapperHistory=new QueryWrapper<>();
            queryWrapperHistory.lambda().select(EduhHouseDetail::getHouseId).eq(EduhHouseDetail::getRealProperty,encrypt);
            List<EduhHouseDetail> eduhHouseDetails = eduhHouseDetailService.list(queryWrapperHistory);
            if (CollectionUtils.isEmpty(eduhHouseDetails)){
                flag=true;
            }else {
                flag=false;
                houseIdList=eduhHouseDetails.stream().map(EduhHouseDetail::getHouseId).distinct().collect(Collectors.toList());
            }
        }else{
            flag=false;
            houseIdList=details.stream().map(EduHouseDetail::getHouseId).distinct().collect(Collectors.toList());
        }

        QueryWrapper<EduStudentHouse> houseQueryWrapper = new QueryWrapper<>();
        int nowYear = DateUtil.thisYear();
        houseQueryWrapper
                .lambda()
                .eq(flag,EduStudentHouse::getRealProperty, vo.getRealProperty())
                .in(!flag,EduStudentHouse::getHouseId, houseIdList)
                .ge(EduStudentHouse::getYear, nowYear - 10)
                .eq(EduStudentHouse::getStatus, BoolEnum.TRUE.getType())
                .orderByDesc(EduStudentHouse::getYear);;
        List<EduStudentHouse> list = this.list(houseQueryWrapper);
        if(CollectionUtils.isEmpty(list)){
            QueryWrapper<EduHouse> eduHouseQueryWrapper = new QueryWrapper<>();
            eduHouseQueryWrapper.lambda().eq(flag, EduHouse::getRealProperty, vo.getRealProperty())
                    .in(!flag, EduHouse::getHouseId, houseIdList);
            List<EduHouse> houseList = eduHouseService.list(eduHouseQueryWrapper);

            if (CollectionUtils.isEmpty(houseList)) {
                QueryWrapper<EduhHouse> eduhHouseQueryWrapper = new QueryWrapper<>();
                eduhHouseQueryWrapper.lambda().eq(flag, EduhHouse::getRealProperty, encrypt)
                        .in(!flag, EduhHouse::getHouseId, houseIdList);
                List<EduhHouse> eduhHouses = eduhHouseService.list(eduhHouseQueryWrapper);
                if (CollectionUtils.isEmpty(eduhHouses)){
                    return new ArrayList<>();
                }else {
                    //判断是否加密，解密
                    for (EduhHouse eduhHouse : eduhHouses) {
                        if ("1".equals(eduhHouse.getEncryptFlag())){
                            eduhHouseService.decrypt(eduhHouse);
                        }
                    }
                    houseList = Convert.toList(EduHouse.class, eduhHouses);
                }
            }
            list = new ArrayList<>();
            for (EduHouse eduHouse : houseList) {
                if (StringUtils.isNotBlank(eduHouse.getRealPropertyNum())) {
                    QueryWrapper<EduStudentHouse> houseQueryWrapper1 = new QueryWrapper<>();
                    houseQueryWrapper1
                            .lambda()
                            .eq(EduStudentHouse::getRealPropertyNum, eduHouse.getRealPropertyNum())
                            .ge(EduStudentHouse::getYear, nowYear - 10)
                            .eq(EduStudentHouse::getStatus, BoolEnum.TRUE.getType())
                            .orderByDesc(EduStudentHouse::getYear);
                    List<EduStudentHouse> list1 = this.list(houseQueryWrapper1);
                    if (!CollectionUtils.isEmpty(list1)) {
                        list.addAll(list1);
                    }
                } else {
                    if (StringUtils.isNotBlank(eduHouse.getAddress())) {
                        QueryWrapper<EduStudentHouse> houseQueryWrapper2 = new QueryWrapper<>();
                        houseQueryWrapper2
                                .lambda()
                                .eq(EduStudentHouse::getAddress, eduHouse.getAddress())
                                .ge(EduStudentHouse::getYear, nowYear - 10)
                                .eq(EduStudentHouse::getStatus, BoolEnum.TRUE.getType())
                                .orderByDesc(EduStudentHouse::getYear);
                        List<EduStudentHouse> list2 = this.list(houseQueryWrapper2);
                        if (!CollectionUtils.isEmpty(list2)) {
                            list.addAll(list2);
                        }
                    }
                }
            }
        }
        if (CollectionUtils.isEmpty(list)){
            return new ArrayList<>();
        }
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        String areaCode=list.get(0).getAreaCode();
        if(StringUtils.isBlank(areaCode)){
            throw new AppException("数据异常：房产使用所属行政区划不能为空");
        }
        CommonVO commonVO=new CommonVO();
        commonVO.setParamKey("local_house_year");
        commonVO.setAreaCode(areaCode);
        String maxValue=commonIntegration.getValueByKey(commonVO);
        int max=StringUtils.isBlank(maxValue)?3:Integer.valueOf(maxValue);
        List<EduStudentHouseVO> resultList = new ArrayList<>();
        for(EduStudentHouse eduStudentHouse:list){
            if(nowYear-eduStudentHouse.getYear()<max){
                int i = 0;
                if (StringUtils.isBlank(eduStudentHouse.getRealPropertyNum())) {
                    for (EduStudentHouse eduStudentHouse1 : list) {
                        if (StringUtils.isBlank(eduStudentHouse1.getRealPropertyNum())) {
                            if (eduStudentHouse.getAddress().equalsIgnoreCase(eduStudentHouse1.getAddress())) {
                                i = i + 1;
                            }
                        }
                    }
                }
                if (i > 1) {
                    continue;
                }
                EduStudentHouseVO eduStudentHouseVO=Convert.convert(EduStudentHouseVO.class,eduStudentHouse);
                resultList.add(eduStudentHouseVO);
            }
        }


        return resultList;
    }
}
